package com.atom.module.mvvm.extren

import androidx.annotation.CheckResult
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleObserver
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.OnLifecycleEvent
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.channels.awaitClose
import kotlinx.coroutines.flow.callbackFlow

/**
 * lifecycle.events()
 *     .filter { it == Lifecycle.Event.ON_CREATE }
 *     .onEach { event ->
 *          // handle Lifecycle.Event.ON_CREATE event
 *     }
 *     .launchIn(uiScope)
 */
@CheckResult
@OptIn(ExperimentalCoroutinesApi::class)
public fun Lifecycle.events() = callbackFlow <Lifecycle.Event>{
    checkMainThread()
    val observer = object : LifecycleObserver {
        @Suppress("UNUSED_PARAMETER")
        @OnLifecycleEvent(Lifecycle.Event.ON_ANY)
        fun onEvent(owner: LifecycleOwner, event: Lifecycle.Event) {
            trySend(event)
        }
    }
    addObserver(observer)
    awaitClose { removeObserver(observer) }
}